package com.hundsun.yr.universal.p2p.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.SpannableStringBuilderUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView.OnLoadMoreListener;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.MyLoanListBeen;
import com.hundsun.yr.universal.p2p.bean.TradeRecord;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.WaitPayListPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.LoanDetailActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @version V1.0
 * @Title: WaitPayFragment.java
 * @Description: 我的借款-已还借款
 * @date 2016-1-5 下午2:51:14
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class ReturnLoanFragment extends BaseFragment implements BaseListView,
        UpdateItem<MyLoanListBeen>, OnLoadMoreListener,
        OnRefreshListener, OnItemClickListener {

    /**
     * 适配器
     **/
    private HolderAdapter<MyLoanListBeen> mAdapter = null;
    /**
     * 上拉列表（listView）
     **/
    private HSLoadMoreListView lv_inhand = null;
    /**
     * 下拉容器
     **/
    private HSSwipeRefreshLayout hsSwipeRefreshLayout_inhand = null;
    /**
     * 索引偏移量
     **/
    private int start = 0;
    /**
     * 数据集合
     **/
    private List<MyLoanListBeen> data = new ArrayList<MyLoanListBeen>();
    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**定时器容器**/
    /**
     * zwgt时间
     **/
    private String zwgt_data;
    private int lastVisiblePosition;
    private Long time;
    private LayoutInflater mInflater;
    private RelativeLayout headerView;

    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        loadingData();
    }

    @Override
    protected void onUserVisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand = findView(R.id.hsSwipeRefreshLayout_returnloan);
        return hsSwipeRefreshLayout_inhand;
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        if (mPresenter == null) {
            mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        }
        if (hsSwipeRefreshLayout_inhand == null) {
            hsSwipeRefreshLayout_inhand = (HSSwipeRefreshLayout) getActivity().findViewById(R.id.hsSwipeRefreshLayout_returnloan);
        }
        lv_inhand = findView(R.id.lv_returnloan);

        ViewCreatorHelper<MyLoanListBeen> creatorHelper = new ViewCreatorHelper<MyLoanListBeen>(R.layout.item_my_loan_all, this);
        mAdapter = new HolderAdapter<MyLoanListBeen>(mContext, creatorHelper.viewCreator());

        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        headerView = (RelativeLayout) mInflater.inflate(R.layout.item_header_10dp, lv_inhand, false);
        lv_inhand.addHeaderView(headerView);

        lv_inhand.setAdapter(mAdapter);

        hsSwipeRefreshLayout_inhand.setOnRefreshListener(this);
        lv_inhand.setOnLoadMoreListener(this);
        lv_inhand.setOnItemClickListener(this);

    }

    /**
     * 加载数据
     */
    private void loadingData() {
        start = 0;
        hsSwipeRefreshLayout_inhand.setRefreshing(true);
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_return_loan;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void refreshListData(List<T> result) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand.setRefreshing(false);
        lv_inhand.setLoadMoreEnabled(true);
        if(data.size() > 0) data.clear();
        if(result!=null){
            data.addAll((Collection<? extends MyLoanListBeen>) result);
        }
        mAdapter.update(data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void addMoreListData(List<T> result) {
        // TODO Auto-generated method stub
        lv_inhand.onLoadMoreComplete();

        if(result!=null && result.size() > 0){
            data.addAll((Collection<? extends MyLoanListBeen>) result);
            lv_inhand.setLoadMoreEnabled(true);
        } else {
            lv_inhand.setLoadMoreEnabled(false);
        }
        mAdapter.update(data);
    }

    @Override
    public <T> void onFailure(String task_name) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand.setRefreshing(false);
        lv_inhand.onLoadMoreComplete();
//        if (data.size() > 0) data.clear();
//        lv_inhand.setAdapter(mAdapter);
//        mAdapter.update(data);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);

        lastVisiblePosition = lv_inhand.getLastVisiblePosition();
        time = Long.valueOf(data.get(lastVisiblePosition - 2).ctime);

        Logs.e("lastVisiblePosition: " + lastVisiblePosition + "time" + time);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.LOAN_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4 + "&ctime=" + time,
                Constants.EVENT_LOAD_MORE_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.LOAN_LIST + "?type=" + 4 + "&ctime=" + time,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void refreshItem(View view, int position, final MyLoanListBeen invest) {
        /**还款利率**/
        TextView tv_annualincome = findView(view, R.id.tv_annualincome);
        SpannableStringBuilder spaBuilder;
        if (invest.debt_rate != null && !invest.debt_rate.isEmpty()){
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    (CommTool.keep1Digits(invest.debt_rate) +  "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
            tv_annualincome.setText(spaBuilder);
        } else {
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    ("0" +  "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
            tv_annualincome.setText(spaBuilder);
        }

        /**营销商品名称**/
        TextView tv_title = findView(view, R.id.tv_title);
        if (invest.prdname != null && !invest.prdname.isEmpty()) {
            tv_title.setText(invest.prdname);
        } else {
            tv_title.setText("申请编号" + invest.uuid);
        }

        /**募集总额|申请金额**/
        TextView tv_income = findView(view, R.id.tv_income);
        tv_income.setText(SpannableStringBuilderUtils.sizeSpan(getString(R.string._yuan,CommTool.keep2Digits(invest.true_debt)), getString(R.string.yuan), 12));

        /**募集状态**/
        TextView tv_prd_progress = findView(view, R.id.tv_prd_progress);
        tv_prd_progress.setText(invest.getPrdprogress());

        /**还款方式  右下**/
        TextView tv_incomemonet = findView(view, R.id.tv_incomemonet);
        tv_incomemonet.setText(invest.getPayMethod(mContext));
        tv_incomemonet.setVisibility(View.VISIBLE);

        /**下一期还款额度  右下**/
        TextView tv_next_amount = findView(view, R.id.tv_next_amount);
        tv_next_amount.setVisibility(View.GONE);


        /**撤销按钮  右中**/
        HSButton btn_cancel = findView(view, R.id.btn_prd_progress);
        btn_cancel.setVisibility(View.GONE);

        /**募集总额|申请金额  中**/
        TextView tv_raise_amount = findView(view, R.id.tv_raise_amount);

        /**还款进度|借款期限  左下**/
        TextView tv_invset_money = findView(view, R.id.tv_invset_money);
        SpannableStringBuilder spaBuilder_tv_invset_money = (SpannableStringBuilderUtils.colorSpan
                (getString(R.string._term_dialog_title, invest.getTerm()), invest.getTerm(), mContext.getResources().getColor(R.color.black)));
        tv_invset_money.setText(spaBuilder_tv_invset_money);


        /**下期还款  右下  偏上**/
        TextView tv_next_term = findView(view, R.id.tv_next_term);
        tv_next_term.setVisibility(View.GONE);
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (isFastDoubleClick()){
            return;
        }

        if (position == 0 ||position > data.size()) return;
        Bundle bundle = new Bundle();
        //携带所有的数据过去
        bundle.putSerializable(Extras.DATA, data.get(position - 1));
        readyGo(LoanDetailActivity.class, bundle);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}

